//
//  WJPurchaseViewController2.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/11/6.
//

import UIKit
import SnapKit
import Lottie
import StoreKit

class WJPurchaseViewController2: UIViewController, WJPurchaseViewControllerProtocol {
    
    private var products: [SKProduct] = [] {
        didSet {
            setDisplayProducts()
        }
    }
    
    private var displayProduct: SKProduct?
    private var showDiscount: Bool = true
    
    var dimissAction:(() -> Void)?
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: "#061B31")
        setupNavigationBar()
        setupLayout()
        addTapGesture()
        WJPurchaseManager.shared.delegate = self
        loadProducts()
    }
    
    // MARK: - 设置导航栏
    private func setupNavigationBar() {
        // 左侧关闭按钮
        let leftBar = UIBarButtonItem(
            image: UIImage(named: "Icon_line_close")?.withRenderingMode(.alwaysTemplate),
            style: .plain,
            target: self,
            action: #selector(clickLeftBarItemAction(_:))
        )
        leftBar.tintColor = .white
        navigationItem.leftBarButtonItem = leftBar
        
        // 右侧 "Restore" 按钮
        let rightBtn = UIButton(type: .custom)
        rightBtn.setTitle("Restore", for: .normal)
        rightBtn.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        rightBtn.layer.cornerRadius = 16
        rightBtn.layer.borderColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.6).cgColor
        rightBtn.layer.borderWidth = 1
        rightBtn.addTarget(self, action: #selector(restoreButtonTapped(_:)), for: .touchUpInside)
        rightBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 32)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
    }
    
    func loadProducts() {
        WJProgressHUD.showLoading()
        let identifiers: Set<String> = Set(WJSku.allCases.map { $0.rawValue })
        WJPurchaseManager.shared.fetchProducts(identifiers: identifiers)
    }
    
    func setDisplayProducts() {
        let productIds = RemoteConfigValues.skus
        self.displayProduct = productIds
            .compactMap { productId in
                products.first { $0.productIdentifier == productId }
            }
            .first
    }
    
    func updatePurchaseDisplayInfo() {
        configureText()
    }
    
    private func validateOfferEligibility() {
        WJUserManager.shared.shouldShowOffer {  [weak self] show in
            WJProgressHUD.dismiss()
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.showDiscount = show
                self.updatePurchaseDisplayInfo()
            }
        }
    }
    
    // MARK: // UI Compents
    lazy var scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.showsVerticalScrollIndicator = false
        return sv
    }()
    
    lazy var contentView: UIView = {
        let view = UIView()
        return view
    }()
    
    lazy var signLabel: UILabel = {
        let label = UILabel()
        label.text = "Sign"
        label.backgroundColor = UIColor(hex: "#1F87F6")
        label.textColor = UIColor(hex: "#FFFFFF")
        label.textAlignment = .center
        label.layer.masksToBounds = true
        label.layer.cornerRadius = 8
        label.font = UIFont.systemFont(ofSize: 28, weight: .semibold)
        return label
    }()
    
    lazy var documentLabel: UILabel = {
        let label = UILabel()
        label.text = "Documents Effortlessly"
        label.textColor = UIColor(hex: "#FFFFFF")
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 28, weight: .semibold)
        return label
    }()
    
    lazy var tapContinueLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 2
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 28, weight: .semibold)
        label.isUserInteractionEnabled = true
        return label
    }()
    
    // 功能特性标题
    lazy var featuresTitleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .center
        label.textColor = UIColor(hex: "#FFFFFF")
        label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        return label
    }()
    
    // 功能特性描述
    lazy var featuresDescriptionLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .center
        label.textColor = UIColor(hex: "#FFFFFF")
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        return label
    }()
    
    lazy var detailLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .center
        label.textColor = UIColor(hex: "#FFFFFF", alpha: 0.6)
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
    
    private lazy var animationView: LottieAnimationView = {
        let animationView = LottieAnimationView(name: "animation1")
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = .loop
        animationView.animationSpeed = 1.0
        animationView.play()
        return animationView
    }()
    
    private lazy var continueButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Continue", for: .normal)
        button.backgroundColor = UIColor(hex: "#1F87F6")
        if let backgroundImage = UIImage(named: "button_layer") {
            let capInsets = UIEdgeInsets(top: 0, left: 32, bottom: 0, right: 32)
            let resizableImage = backgroundImage.resizableImage(withCapInsets: capInsets, resizingMode: .stretch)
            button.setBackgroundImage(resizableImage, for: .normal)
        }
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.titleLabel?.font = UIFont.montserratMedium(20)
        button.layer.cornerRadius = 32
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(continueAction(_:)), for: .touchUpInside)
        return button
    }()
    
    private lazy var privacyLabel: UILabel = {
        let label = UILabel()
        label.text = "Privacy"
        label.textColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.7)
        label.font = UIFont.systemFont(ofSize: 10)
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(privacyTapped)))
        return label
    }()
    
    private lazy var termsLabel: UILabel = {
        let label = UILabel()
        label.text = "Terms"
        label.textColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.7)
        label.font = UIFont.systemFont(ofSize: 10)
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(termsTapped)))
        return label
    }()
    
    private lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.7)
        return view
    }()
    
    lazy var hStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fill
        stackView.alignment = .center
        stackView.spacing = 12.0
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        stackView.addArrangedSubview(privacyLabel)
        stackView.addArrangedSubview(lineView)
        stackView.addArrangedSubview(termsLabel)
        
        // 使用 SnapKit 设置 lineView 尺寸
        lineView.snp.makeConstraints { make in
            make.width.equalTo(2.0 / UIScreen.main.scale) // 物理像素2px
            make.height.equalTo(12) // 合适的高度
        }
        return stackView
    }()
    
    // MARK: - Layout
    private func setupLayout() {
        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        contentView.addSubview(signLabel)
        contentView.addSubview(documentLabel)
        contentView.addSubview(animationView)
        contentView.addSubview(tapContinueLabel)
        contentView.addSubview(featuresDescriptionLabel)
        contentView.addSubview(featuresTitleLabel)
        contentView.addSubview(detailLabel)
        contentView.addSubview(hStackView)
        view.addSubview(continueButton)
        
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalToSuperview().offset(safeAreaTop + 40)
            make.bottom.equalTo(continueButton.snp.top).offset(-10)
        }
        
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(scrollView)
            // 关键：contentView高度等于scrollView，但优先级较低，当内容多时可以自动扩展
            make.height.equalTo(scrollView).priority(.low)
        }
        
        // 创建容器视图来包裹所有需要从底部显示的内容
        let bottomContainerView = UIView()
        contentView.addSubview(bottomContainerView)
        
        // 将需要从底部显示的内容添加到容器中
        bottomContainerView.addSubview(animationView)
        bottomContainerView.addSubview(tapContinueLabel)
        bottomContainerView.addSubview(featuresTitleLabel)
        bottomContainerView.addSubview(featuresDescriptionLabel)
        bottomContainerView.addSubview(detailLabel)
        bottomContainerView.addSubview(hStackView)
        
        // 顶部固定内容
        signLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(30)
            make.centerX.equalToSuperview()
            make.width.equalTo(84)
            make.height.equalTo(44)
        }
        
        documentLabel.snp.makeConstraints { make in
            make.top.equalTo(signLabel.snp.bottom).offset(10)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(39)
        }
        
        // 底部容器视图约束
        bottomContainerView.snp.makeConstraints { make in
            make.top.equalTo(documentLabel.snp.bottom)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
            // 关键：设置最小高度，确保容器有足够空间
            make.height.greaterThanOrEqualTo(0)
        }
        
        // 底部容器内的内容从底部开始布局
        hStackView.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-20)
            make.centerX.equalToSuperview()
            make.height.equalTo(30)
        }
        
        detailLabel.snp.makeConstraints { make in
            make.bottom.equalTo(hStackView.snp.top).offset(-10)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        featuresDescriptionLabel.snp.makeConstraints { make in
            make.bottom.equalTo(detailLabel.snp.top).offset(-15)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        featuresTitleLabel.snp.makeConstraints { make in
            make.bottom.equalTo(featuresDescriptionLabel.snp.top).offset(-15)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        tapContinueLabel.snp.makeConstraints { make in
            make.bottom.equalTo(featuresTitleLabel.snp.top).offset(-20)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        animationView.snp.makeConstraints { make in
            make.bottom.equalTo(tapContinueLabel.snp.top).offset(-20)
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.greaterThanOrEqualToSuperview().offset(10)
            make.height.equalTo(200 * aScale) // 设置固定高度
        }
        
        continueButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-safeAreaBottom)
            make.leading.trailing.equalToSuperview().inset(32)
            make.height.equalTo(64)
        }
        
        // 添加一个关键约束：当内容高度小于scrollView时，底部容器顶部与scrollView底部对齐
        bottomContainerView.snp.makeConstraints { make in
            make.top.greaterThanOrEqualTo(documentLabel.snp.bottom)
        }
    }
    
    // MARK: - Text & Gesture
    private func configureText() {
        guard let currentProduct = displayProduct else { return }
        guard let sku = WJSku(rawValue: currentProduct.productIdentifier) else { return }
        
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        numberFormatter.locale = currentProduct.priceLocale

        guard let price = numberFormatter.string(from: currentProduct.price) else  {
            return
        }
        
        var fullText = ""
        var featureText = ""
        var detailPriceFormat = ""
        switch sku {
        case .yearly, .yearlyDiscount:
            fullText = "Tap Continue for 1-year access"
            featureText = "Full access to all cleaning features \n1 Year for \(price)"
            detailPriceFormat = "\(price) a year"
        case .weekly:
            fullText = "Tap Continue for 7-day access"
            featureText = "Full access to all cleaning features \n1 Week for \(price)"
            detailPriceFormat = "\(price) a week"
        case .weeklyFree:
            fullText = "Tap Continue for 7-day access"
            if showDiscount {
                var freedays = 3
                if let days = WJUserManager.shared.getIntroductoryPriceDurationInDays(product: currentProduct) {
                    freedays = days
                }
                featureText = "Full access to all cleaning features \nfor \(freedays) days free"
            } else {
                featureText = "Full access to all cleaning features \n1 Week for \(price)"
            }

            detailPriceFormat = "\(price) a week"
        case .weeklyDiscount:
            fullText = "Tap Continue for 7-day access"

            if showDiscount {
                
                if let introductoryPrice = currentProduct.introductoryPrice?.price,
                    let discountPrice = numberFormatter.string(from: introductoryPrice) {
                    featureText = "Full access to all cleaning features \n1 Week for \(discountPrice)"
                } else {
                    featureText = "Full access to all cleaning features \n1 Week for \(price)"
                }
            } else {
                featureText = "Full access to all cleaning features \n1 Week for \(price)"
            }

            detailPriceFormat = "\(price) a week"
        }

        // 创建富文本
        let attributedString = NSMutableAttributedString(string: fullText)
        
        // 设置整体文字颜色为白色
        attributedString.addAttribute(.foregroundColor, value: UIColor(hex: "#FFFFFF"),
                                      range: NSRange(location: 0, length: attributedString.length))
        
        // 找到 "Continue" 的位置并设置为蓝色
        let continueRange = (fullText as NSString).range(of: "Continue")
        if continueRange.location != NSNotFound {
            attributedString.addAttribute(.foregroundColor, value: UIColor(hex: "#1F87F6"),
                                          range: continueRange)
        }
        
        // 创建图片附件
        if let iconImage = UIImage(named: "purchase_Icon_line_sign") {
            let attachment = NSTextAttachment()
            let imageSize = CGSize(width: 24, height: 24)
            attachment.image = iconImage.withTintColor(UIColor(hex: "#FFFFFF"))
            
            // 垂直对齐调整，使图标与文字居中对齐
            let yOffset: CGFloat = -2.0 // 微调垂直位置
            attachment.bounds = CGRect(x: 0, y: yOffset, width: imageSize.width, height: imageSize.height)
            
            // 创建图片的富文本
            let imageAttributedString = NSAttributedString(attachment: attachment)
            
            // 在文字后面添加一个空格和图标
            attributedString.append(NSAttributedString(string: " ")) // 添加一个空格
            attributedString.append(imageAttributedString)
        }
        
        tapContinueLabel.attributedText = attributedString
        
        // 功能特性标题
        featuresTitleLabel.text = featureText
        // 功能特性描述
        featuresDescriptionLabel.text = "Features include smart signing, secure storage, sync & more Cancel anytime, hassle free. Request a refund if you're not 100% satisfied."
        
        // 订阅条款
        if showDiscount {
            detailLabel.text = """
            Subscription payments will be charged to your Apple account at confirmation of your purchase and upon commencement of each renewal term. The subscription will automatically renew at \(detailPriceFormat). You can cancel your subscription in the Apple account settings at least 24 hours before the end of each current subscription period. The cancellation will take effect the day after the last day of the current subscription period and you will be downgraded to the free service. Any unused portion of the introduction offer will be forfeited if you purchase any other premium subscription during the introduction period.
            """
        } else {
            detailLabel.text = """
            - Billed \(detailPriceFormat). Subscription payments will be charged to your Apple account at confirmation of your purchase and upon commencement of each renewal term.  You can cancel your subscription in the Apple account settings at least 24 hours before the end of each current subscription period. The cancellation will take effect the day after the last day of the current subscription period and you will be downgraded to the free service. Any unused portion of the introduction offer will be forfeited if you purchase any other premium subscription during the introduction period.
            """
        }
    }
    
    private func addTapGesture() {
        // 给标题标签添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleContinueTapped))
        tapContinueLabel.addGestureRecognizer(tapGesture)
    }
    
    // MARK: - Actions
    @objc private func handleContinueTapped() {

        purchase()
    }
    
    // MARK: - 按钮/手势事件
    @objc func clickLeftBarItemAction(_ item: UIBarButtonItem) {
        dismiss(animated: true) { [weak self] in
            guard let self = self else { return }
            dimissAction?()
        }
    }
    
    @objc func restoreButtonTapped(_ button: UIButton) {
        WJProgressHUD.showLoading()
        WJPurchaseManager.shared.restorePurchases()
    }
    
    @objc func privacyTapped() {
        // 隐私政策跳转
        if let url = URL(string: "https://www.freeprivacypolicy.com/live/b4baff6e-61f8-491e-b138-b13696060fd3") {
            UIApplication.shared.open(url)
        }
    }
    
    @objc func termsTapped() {
        // 条款跳转
        if let url = URL(string: "https://www.freeprivacypolicy.com/live/f2a037ca-a61e-4802-a0b5-8e5785c44762") {
            UIApplication.shared.open(url)
        }
    }
    
    @objc func continueAction(_ button: UIButton) {
        purchase()
    }
    
    func purchase() {
        WJProgressHUD.showLoading()
        guard let selectedProduct = displayProduct else {
            WJProgressHUD.showInfo(with: "failed")
            return
        }
        WJPurchaseManager.shared.purchaseProduct(selectedProduct)
    }
}

extension WJPurchaseViewController2: WJPurchaseManagerDelegate {
    func productsLoaded(products: [SKProduct]) {
        self.products = products
        validateOfferEligibility()
    }
    
    func purchaseCompleted(result: WJPurchaseResult) {
        switch result {
        case .success(_):
            WJProgressHUD.showInfo(with: "Purchase successful")
           dismiss(animated: true)
            
        case .failure(let error):
            WJProgressHUD.showInfo(with: error)
            
        case .cancelled:
            WJProgressHUD.showInfo(with: "Purchase Canceled")
        case .restored:
            WJProgressHUD.showInfo(with: "Restore successful")
        case .restoreFailure(let error):
            WJProgressHUD.showInfo(with: error)
        }
    }
    
    func productsRequestFailed(error: String) {
        WJProgressHUD.showInfo(with: error)
    }
}

